const fs = require('fs');
const path = require('path');
const {unlink, rmdir, readdir, stat} = require('node:fs/promises')
const {join} = require('node:path')

const outPath = './pngs'

async function main() {
  if (fs.existsSync(outPath)) {
    await removeFile(outPath)
  }
  const filePathList = traverseFolderSync('./', [])
  console.log("filePathList", filePathList)

  if (!fs.existsSync(outPath)) {
    mkdir(outPath)
    mkdir(path.join(outPath, './all'))

  }
  for (const file of filePathList) {
    dealWithFile(file)
  }
}

function mkdir(dir) {
  try {
    fs.mkdirSync(dir)
  } catch (err) {
  }
}

function traverseFolderSync(path, filePathList) {
  const files = fs.readdirSync(path);

  files.forEach((file) => {
    const filePath = path + '/' + file;
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      traverseFolderSync(filePath, filePathList); // 递归遍历子文件夹
    } else {
      filePathList.push(filePath); // 处理文件
    }
  });
  return filePathList;
}

function dealWithFile(filePath) {
  console.log("处理文件: filePath", filePath)
  if (filePath.indexOf(".png") === -1) return
  const baseName = path.basename(filePath)
  const destAllPath = path.join(outPath, 'all', baseName)
  const destPath = path.join(outPath, filePath)
  const dirName = path.dirname(destPath)
  const dirAllName = path.dirname(destAllPath)
  mkdir(dirName)
  mkdir(dirAllName)
  fs.copyFileSync(filePath, destAllPath)
  fs.copyFileSync(filePath, destPath)

}


const removeFile = (path) => {
  return new Promise((resolve, reject) => {
    if (fs.existsSync(path)) {

    }
    checkStat(path)
      .then(isFile => {
        if (isFile) {
          return unlink(path)
        }
        return readdir(path)
      })
      .then(files => {
        if (Array.isArray(files)) {
          const removeFiles = files.map(file => removeFile(join(path, file)))
          return Promise.all(removeFiles)
        }
      })
      .then((files) => {
        if (Array.isArray(files)) {
          rmdir(path)
            .then(resolve, reject)
        } else {
          resolve()
        }
      })
  })
}

const checkStat = (path) => {
  return new Promise((resolve, reject) => {
    stat(path)
      .then(stat => {
        resolve(stat.isFile())
      })
      .catch(err => {
        reject(err)
      })
  })
}

main()